<template>

    <div class="merchant-page">
        <div>
           <el-form>
                <el-form-item label="任务编号：">
                    <el-input placeholder="请输入任务编号" v-model="searchForm.taskCode" size="small" clearable></el-input>
                </el-form-item>
                <el-form-item label="商户号：">
                    <el-input placeholder="请输入商户号" v-model="searchForm.merchantPhone" size="small" clearable></el-input>
                </el-form-item>
                <el-form-item label="店铺名称：">
                    <el-input placeholder="请输入店铺名称" v-model="searchForm.shopName" size="small" clearable></el-input>
                </el-form-item>
                <el-form-item label="我的推广员：">
                    <el-select v-model="searchForm.promoterNext" placeholder="请选择推广员" size="small">
                        <el-option label="全部" value=""></el-option>
                        <el-option v-for="(item, index) in promoterListData" :key="index" :label="item.phone" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="资金类型：">
                   <el-select v-model="searchForm.financeType" placeholder="请选择资金类型" size="small">
                       <el-option label="全部" value=""></el-option>
                       <el-option v-for="(item, index) in financeTypeData" :key="index" :label="item.name" :value="item.id"></el-option>
                   </el-select>
               </el-form-item>
                <el-form-item label="创建时间 ：">
                    <div class="block">
                    <el-date-picker size="small" v-model="searchTime" type="datetimerange" @change="changeTime" :default-time="['00:00:00', '23:59:59']" range-separator="至" start-placeholder="开始日期"
                    :picker-options="pickerOptions"  end-placeholder="结束日期"></el-date-picker>
                    </div>
                </el-form-item>
                <!-- <el-form-item label="任务开始时间 ：">
                    <div class="block">
                    <el-date-picker size="small" v-model="searchTaskStartTime" type="datetimerange" @change="changeTaskStartTime" :default-time="['00:00:00', '23:59:59']" range-separator="至" start-placeholder="开始日期"
                    :picker-options="pickerOptions"  end-placeholder="结束日期"></el-date-picker>
                    </div>
                </el-form-item> -->
               <el-form-item>
                   <el-button class="search-btn" @click="searchData()">查&nbsp;&nbsp;询</el-button>
               </el-form-item>

           </el-form>
       </div>
       <div>
           <el-table :data="tableData" border>
               <el-table-column prop="task_code"  label="任务编号"></el-table-column>
               <!-- <el-table-column prop="task_start_time"  label="任务开始时间"></el-table-column> -->
               <el-table-column prop="phone"  label="商户号"></el-table-column>
               <el-table-column prop="shop_type_name"  label="店铺类型/店铺名称"></el-table-column>
               <el-table-column prop="finance_type_name" label="资金类型"></el-table-column>
               <el-table-column prop="commission_change" label="佣金变动"></el-table-column>
               <el-table-column prop="commission_balance" label="余额"></el-table-column>
               <el-table-column prop="promoter_phone"  label="推广员账号"></el-table-column>
               <el-table-column prop="remark" label="备注"></el-table-column>
               <el-table-column prop="create_time" label="创建时间"></el-table-column>
           </el-table>
           <el-table :data="allTableData" id="export" v-show="false" border>
               <el-table-column prop="task_code"  label="任务编号"></el-table-column>
               <!-- <el-table-column prop="task_start_time"  label="任务开始时间"></el-table-column> -->
               <el-table-column prop="phone"  label="商户号"></el-table-column>
               <el-table-column prop="shop_type_name"  label="店铺类型/店铺名称"></el-table-column>
               <el-table-column prop="finance_type_name" label="资金类型"></el-table-column>
               <el-table-column prop="commission_change" label="佣金变动"></el-table-column>
               <el-table-column prop="commission_balance" label="余额"></el-table-column>
                <el-table-column prop="promoter_phone"  label="推广员账号"></el-table-column>
               <el-table-column prop="remark" label="备注"></el-table-column>
               <el-table-column prop="create_time" label="创建时间"></el-table-column>
           </el-table>
           <div class="export-box">
             <el-button class="export-btn" @click="exportExcel">导出</el-button>
           </div>
            <div class="block" style="margin: 20px 0px; text-align: right;">
            	<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchForm.page"
            	 :page-sizes="[10, 15, 20, 25]" :page-size="searchForm.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageTotal"></el-pagination>
            </div>
       </div>
    </div>

</template>
<script>
import {apiPromoterCommissionList,apiPromoterList} from '../../request/api'
import FileSaver from 'file-saver'
  import XLSX from 'xlsx'
    export default {
        data(){
            return {
                tableData:[],
                searchForm: {
                    page: 1,
                    pageSize: 10,
                    token: window.sessionStorage.getItem("token"),
                    financeType: '',
                    merchantPhone: '',
                    createTime: '',
                    // taskStartTime: '',
                    shopName: '',
                    taskCode: '',
                    promoterNext: ''
                },
                pageTotal: 0,
                allCommission: 0,
                financeTypeData: [{
                    id: '50',
                    name: '推广员佣金收入'
                },{
                    id: '51',
                    name: '推广员分佣收入'
                },{
                    id: '52',
                    name: '推广员佣金返还'
                },{
                    id: '53',
                    name: '推广员分佣返还'
                }],
                searchTime: [],
                searchTaskStartTime: [],
                pickerOptions: {
                  disabledDate(time) {
                     let curDate = (new Date()).getTime();
                     let three = 90 * 24 * 3600 * 1000;
                     let threeMonths = curDate - three;
                     return time.getTime() < threeMonths;
                  },
                },
                allTableData: [],
                promoterListData: []
            }
        },
        created () {
            this.getTableData()
            this.writeCurrentDate()
            this.promoterList()
        },
        methods:{
          promoterList(){
            apiPromoterList({
              token: window.sessionStorage.getItem("token")
            }).then(res =>{
                this.promoterListData = res.msg
            }).catch(res => {

            })
          },
          writeCurrentDate() {
            var now = new Date();
            var startTime = new Date(new Date().toLocaleDateString()).getTime() - 24 * 60 * 60 * 1000 * 6
            var endTime = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1;
            this.searchTime = [startTime,endTime]
            // this.searchTaskStartTime = [startTime,endTime]
            this.searchForm.createTime = this.changeTimestamp(startTime) + ' - ' + this.changeTimestamp(endTime)
            // this.searchForm.taskStartTime = this.changeTimestamp(startTime) + ' - ' + this.changeTimestamp(endTime)
            // this.form.startTime = Math.floor(startTime / 1000)
            // this.form.endTime =  Math.floor(endTime / 1000)
          },
            getTableData (){
              this.$showLoading()
                apiPromoterCommissionList(this.searchForm).then(res =>{
                    this.tableData = res.data
                    this.pageTotal = res.count
                    // this.allCommission = res.msg.history_commission
                    // this.commission = res.msg.commission
                     this.$hideLoading()
                }).catch(res => {
                    this.$hideLoading()
                    this.$message.error('数据加载失败')
                })
            },
            searchData(){
                this.searchForm.page = 1;
                this.getTableData()
            },
            handleSizeChange(val){
                this.searchForm.pageSize = val;
      	        this.getTableData()
            },
            handleCurrentChange(val){
                this.searchForm.page = val;
      	        this.getTableData()
            },
            changeTaskStartTime(val){
              if (this.searchTaskStartTime == null) {
                   this.searchForm.taskStartTime = ''
              } else{
                  const startTimestamp = new Date(val[0]).getTime();
                  const endTimestamp = new Date(val[1]).getTime();
                  if ((endTimestamp - startTimestamp) > 7 * 24 * 60 * 60 * 1000) {
                     this.$message.warning('查询范围不能超过一周');
                     this.writeCurrentDate()
                     return;
                  }
                  this.searchForm.taskStartTime =  this.changeTimestamp(val[0]) + ' - ' +  this.changeTimestamp(val[1])

              }
            },
            changeTime(val){
                if (this.searchTime == null) {
                     this.searchForm.createTime = ''
                } else{
                    const startTimestamp = new Date(val[0]).getTime();
                    const endTimestamp = new Date(val[1]).getTime();
                    if ((endTimestamp - startTimestamp) > 7 * 24 * 60 * 60 * 1000) {
                       this.$message.warning('查询范围不能超过一周');
                       this.writeCurrentDate()
                       return;
                    }
                    this.searchForm.createTime =  this.changeTimestamp(val[0]) + ' - ' +  this.changeTimestamp(val[1])

                }
            },
            changeTimestamp (time){
               var date = new Date(time)
               var Y = date.getFullYear() + '-';
               var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
               var D = (date.getDate() < 10 ? '0' +  date.getDate() : date.getDate()) + ' ';
               var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
               var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
               var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
               return Y + M + D + h + m + s;
            },
            getAllTableData(){
              let data = JSON.parse(JSON.stringify(this.searchForm))
              data.page = 1
              data.pageSize = this.pageTotal
              if (data.pageSize == 0) {
                 this.$message.error('当前表格没有数据可以导出');
                 return
              }
              return new Promise ((resolve) =>{
                this.$showLoading()
                apiPromoterCommissionList(data).then(res =>{
                    this.allTableData = res.msg.capital_flow_list.res
                    resolve(res) ;
                }).catch(res => {
                    this.$hideLoading()
                    this.$message.error('数据量太大，导出失败，请先筛选条件后导出')
                })
              })

            },
            exportExcel (val) {
              if(!this.searchForm.createTime){
                this.$message.error('请先选择创建时间，再进行导出')
                return
              }
              this.$showLoading()
              let uid = window.sessionStorage.getItem("uid")
              let downloadUrl = this.BASE_API_URL + 'baseapi/promoterBase/promoterCommissionExport'
              let downloadParam = '?uid=' + uid + '&financeType=' + this.searchForm.financeType + '&merchantPhone=' + this.searchForm.merchantPhone + '&createTime=' + this.searchForm.createTime
               + '&shopName=' + this.searchForm.shopName  + '&taskCode=' + this.searchForm.taskCode  + '&promoterNext=' + this.searchForm.promoterNext
              window.location.href = downloadUrl + downloadParam
              setTimeout(()=>{
                 this.$hideLoading()
                 this.$message.warning('请耐心等待表格下载')
              },10000)
              return
              var wb = ''
              var xlsxParam = { raw: true }
             this.getAllTableData().then(()=>{
              wb = XLSX.utils.table_to_book(document.querySelector('#export'),xlsxParam)

              /* get binary string as output */
              var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
              try {
                FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '资金流水信息.xlsx')
              } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
              setTimeout(() => {
                this.$hideLoading()
                this.$message.success('下载完成')
              }, 1000);
              return wbout
             })

            }
        }
    }
</script>
<style lang="less" scoped>
@import '../../assets/css/common.css';
@import '../../assets/css/style.less';
.export-box {
  display: inline-block;
  float: left;
  margin-top: 20px;
  .export-btn {
    padding: 8px 15px;
    color: #FFFFFF;
    background: #0e7cee;

  }
}
</style>
